import { createRouter, createWebHashHistory  } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import WelcomeView from '../views/WelcomeView.vue'
import { getToken } from '@/utils/token.js'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  mode: 'hash',
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/',
      name: 'welcome',
      component: WelcomeView,
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/web',
      name: 'web',
      component: () => import('../views/WebView.vue'),
    },
    {
      path: '/mgt',
      name: 'mgt',
      component: () => import('../views/MgtView.vue'),
    },
  ],
})

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken();
  const userStore = useUserStore();

  if (to.path === '/login') {
    next(); // 放行登录页
    return;
  }

  if (!hasToken) {
    next('/login'); // 无 token 跳转登录
    return;
  }

  const userName = userStore.name;
  if (userName) {
    next(); // 已有用户信息，放行
    return;
  }

  try {
    await userStore.getInfo(); // 获取用户信息
    next(); // 成功放行
  } catch (e) {
    console.error('获取用户信息失败:', e.message);
    showToast(e.message)
    next('/login'); // 失败跳转登录
  }
});

export default router
